// 云函数入口文件
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context })

  let body = event
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body)
    } catch (e) {
      return {
        code: -2,
        message: '参数格式错误，body 应为 JSON 字符串',
        error: e.message || e
      }
    }
  }

  // 参数校验
  if (!body.uniIdToken) {
    return {
      code: -1,
      message: '缺少必要参数：uniIdToken'
    }
  }

  try {
    const res = await uniIDIns.checkToken(body.uniIdToken)

    if (res.code !== 0) {
      return res
    }

    return {
      code: 0,
      token: res.token || body.uniIdToken,
      tokenExpired: res.tokenExpired || null
    }
  } catch (e) {
    console.error('服务器错误:', e)
    return {
      code: -4,
      message: '校验失败',
      error: e.message || e
    }
  }
}
